package apisvr

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"gitee.com/linxing_3/sr-core/config"
	"gitee.com/linxing_3/sr-core/server/net/http"

	"gitee.com/linxing_3/sr-core/utils/ip"
	"gitee.com/mkwchecking/sr-admin/pkg/http/middleware"
	"gitee.com/mkwchecking/sr-admin/pkg/plugins/phttp"
	"github.com/go-kratos/kratos/v2/transport"

	// http session
	_ "gitee.com/linxing_3/sr-core/server/net/http/session/memory"
	_ "gitee.com/linxing_3/sr-core/server/net/http/session/redis"
)

func getInternalHttpServer() (*httpWrapper, error) {
	httpSvr, err := phttp.UpsertHttpSvr()
	if err != nil {
		return nil, err
	}

	httpSvr.Use(middleware.ApiRecordMW())

	if err = setStaticDomain(config.Get().HttpServer.Static, httpSvr); err != nil {
		fmt.Println("set static domain error: ", err)
	}
	return &httpWrapper{srv: httpSvr}, nil
}

func setStaticDomain(www string, srv http.IHttpServer) error {
	if www == "" {
		return nil
	}
	fileDir, err := filepath.Abs(www)
	if err != nil {
		return err
	}
	if stat, err := os.Stat(fileDir); err != nil {
		return err
	} else if !stat.IsDir() {
		return fmt.Errorf("static path %s is not a directory", www)
	}

	srv.Router("").Static("/www", www)
	return nil
}

func printHttpTip() {
	cfg := config.Get().HttpServer
	if cfg == nil {
		return
	}

	fmt.Println("\n\n", "HTTP Server is running on:")
	fmt.Printf("  - http://%s:%s\n", cfg.Host, cfg.Port)
	fmt.Printf("  - http://%s:%s\n", ip.GetLocalHost(), cfg.Port)

}

var _ transport.Server = (*httpWrapper)(nil)

type httpWrapper struct {
	srv http.IHttpServer
}

// Start implements transport.Server.
func (h *httpWrapper) Start(ctx context.Context) error {
	printHttpTip()
	return h.srv.Start(ctx)
}

// Stop implements transport.Server.
func (h *httpWrapper) Stop(ctx context.Context) error {
	return h.srv.Stop(ctx)
}
